//
//  TimePickerView.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/10/26.
//
//  时间选择器，小时：分钟

import UIKit

@objc protocol TimePickerViewDelegate: AnyObject {
    
    /// 回调时间
    /// - Parameters:
    ///   - hour: 小时
    ///   - minute: 分钟
    func timePickerView(hour: Int, minute: Int)
    
    /// 退出
    @objc optional func quit()
}

class TimePickerView: BaseView {
    
    weak var delegate: TimePickerViewDelegate?
    
    private var datas = Array<Array<Int>>()
    private var hours = [Int]()
    private var minutes = [Int]()
    private var hour: Int = 0
    private var minute: Int = 0

    init(hour: Int = 0, minute: Int = 0) {
        super.init(frame: CGRect.zero)
        
        self.hour = hour
        self.minute = minute
        
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(frame: CGRect.zero)
        
        setup()
    }
    
    private func setup() {
        setupUI()
        loadDatas()
    }
    
    func showView() {
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: {
            self.coverView.alpha = 0.4
            self.contentView.transform = CGAffineTransform(translationX: 0, y: -self.contentView.bounds.height)
        }, completion: nil)
    }
    
    func hideView() {
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: {
            self.coverView.alpha = 0.0
            self.contentView.transform = CGAffineTransform.identity
        }, completion: { _ in
            self.removeFromSuperview()
            self.delegate?.quit?()
        })
    }
    
    @objc func cancelView() {
        hideView()
    }
    
    // MARK: - private
    
    private func loadDatas() {
        // 数据源搞多点，弄个假无限循环
        for _ in 0...100 {
            for h in 0...23 {
                hours.append(h)
            }
            
            for m in 0...59 {
                minutes.append(m)
            }
        }
        
        datas.append(hours)
        datas.append(minutes)
        pickerView.reloadAllComponents()
        
        // 让pickerView默认选中中间项
        pickerView.selectRow(24 * 49, inComponent: 0, animated: false)
        pickerView.selectRow(60 * 49, inComponent: 1, animated: false)
    }
    
    private func setupUI() {
        guard let window = UIWindow.key else { return }
        
        window.addSubview(self)
        addSubview(coverView)
        addSubview(contentView)
        contentView.addSubview(pickerView)
        
        self.snp.makeConstraints { make in
            make.right.left.top.bottom.equalTo(window)
        }
        
        coverView.snp.makeConstraints { make in
            make.right.left.top.bottom.equalTo(self)
        }
        contentView.snp.makeConstraints { make in
            make.right.left.equalTo(coverView)
            make.bottom.equalTo(coverView.snp.bottom).offset(250)
            make.height.equalTo(250)
        }
        pickerView.snp.makeConstraints { make in
            make.top.right.left.bottom.equalTo(contentView)
        }
        
        coverView.layoutIfNeeded()
        contentView.layoutIfNeeded()
        pickerView.layoutIfNeeded()
    }
    
    // MARK: - lazy
    
    private lazy var pickerView: UIPickerView = {
        let picker = UIPickerView()
        picker.delegate = self
        picker.dataSource = self
        picker.backgroundColor = UIColor.systemGray5
        return picker
    }()
    
    private lazy var coverView: BaseView = {
        let v = BaseView()
        v.alpha = 0.0
        let tap = UITapGestureRecognizer(target: self, action: #selector(cancelView))
        v.addGestureRecognizer(tap)
        v.backgroundColor = .black
        return v
    }()
    
    private lazy var contentView: BaseView = {
        let v = BaseView()
        return v
    }()
}

extension TimePickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    // 列数
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return datas.count
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return datas[component].count
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 40
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(format: "%02d", datas[component][row])
    }
    
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return 80
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            hour = datas[component][row]
        } else if component == 1 {
            minute = datas[component][row]
        }
        
        delegate?.timePickerView(hour: hour, minute: minute)
    }
}
